package com.example.rwq_test.ThreadPool;

import com.google.common.util.concurrent.*;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 入参为Runnable时，执行Executors.callable()包装后返回的Callable类，返回值Future.get()的结果为null
 * 入参为Runnable和result时，执行Executors.callable()包装后返回的Callable类，返回值Future.get()的结果为传入的result
 * 入参为Callable时，则直接执行的传入的Callable对象的call()方法，返回值Future.get()的结果为call()的返回值
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2024/4/11
 */
public class RunnableThreadPoolExceException {
    public static void main(String[] args) throws InterruptedException {

        ThreadPoolExecutor executorPool = new ThreadPoolExecutor(3, 3, 10,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(7),
                new MyThreadFactory(), new MyRejectedExecutionHandler());

        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorPool);

        for (int i = 0; i < 50; i++) {
            int finalI = i;
            Task task = new Task(finalI);;
            ListenableFuture<Task> listenableFuture = listeningExecutorService.submit(() -> {
                System.out.println(finalI);
                int a = finalI/0;
                task.setAge(task.getNum());
            }, task);

//            ListenableFuture<Task> listenableFuture = (ListenableFuture<Task>) listeningExecutorService.submit(() -> {
//                System.out.println(new Task(finalI));
//                int a = finalI/0;
//            });
            System.out.println("任务提交成功"+ i);
            try {
                //FutureCallBack接口可以对每个任务的成功或失败单独做出响应
                FutureCallback<Task> futureCallback = new FutureCallback<Task>() {
                    @Override
                    public void onSuccess(Task task) {
                        System.out.println("执行结果:" + task);
                    }
                    @Override
                    public void onFailure(Throwable t) {
                        System.out.println("任务执行失败"+t.getMessage());
                    }
                };
                //为任务绑定回调接口
                Futures.addCallback(listenableFuture, futureCallback);

                Task task1 = null;
                try {
                    // 等待任务完成
                    task1 = listenableFuture.get();
                } catch (Exception e) {
                    // 在主线程捕获异常
                    System.err.println("Caught exception task: " + task1 + " in main thread: " + e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        TimeUnit.SECONDS.sleep(200);
        // 主线程继续执行
        System.out.println("Main thread continues.");
        // 关闭线程池
        listeningExecutorService.shutdown();
    }
}
